package com.cqeec.myblog.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.cqeec.myblog.model.Blogger;
import com.cqeec.myblog.model.Photo;
import com.cqeec.myblog.service.PhotoService;
import com.cqeec.myblog.service.PhotoServiceImpl;

@WebServlet("/album/photo/upload.html")
public class UploadPhotoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String albumId = "", photoName = "";
		// 获取博主的ID
		Blogger blogger = (Blogger) request.getSession().getAttribute("blogger");
		// 创建磁盘文件项工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 文件上传到服务器上临时存放的目录(采用默认的)
		// 创建一个Servlet文件上传对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 通过Servlet文件上传对象解析请求对象request
		try {
			List<FileItem> items = upload.parseRequest(request);
			String fieldName;
			for (FileItem item : items) {
				fieldName = item.getFieldName();
				if ("photoFile".equals(fieldName)) {
					// 文件上传字段
					String rootPath = request.getServletContext().getRealPath("/data");
					File file = new File(rootPath + "/" + blogger.getId() + "/" + albumId);
					if (!file.exists()) {
						file.mkdirs();
					}
					System.out.println(file.getAbsolutePath());
					item.write(new File(file.getAbsolutePath() + "/" + item.getName()));
				} else if ("albumId".equals(fieldName)) {
					albumId = item.getString();
				} else if ("photoName".equals(fieldName)) {
					photoName = item.getString();
				}
			}
			System.out.println(albumId + "," + photoName);
			Photo photo = new Photo();
			photo.setId(UUID.randomUUID().toString().toUpperCase());
			photo.setAlbum(albumId);
			photo.setName(photoName);
			photo.setUploadTime(new Date());
			PhotoService photoService = new PhotoServiceImpl();
			photoService.save(photo);
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
